# -*- coding:UTF-8-*-
import time
import datetime
import Adafruit_DHT
from DBTool import *
from Curtain import *

import RPi.GPIO as GPIO

# 定时任务

def get_tem_and_hum():
    sensor = Adafruit_DHT.DHT11
    pin = 23
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    return (humidity, temperature)



def get_light():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(24,GPIO.IN)
    return str(int(not GPIO.input(24)))


def insert_sensor_to_db(humidity, temperature, light):
    db = DBTool()
    now_datetime = datetime.datetime.now(None)
    now_date = now_datetime.strftime('%Y-%m-%d %H:%M:%S')
    ob = [(now_date, str(int(temperature)), str(int(humidity)), light)]
    sql = "insert into tem (date, tem, hum, light) values (?,?,?,?)"
    res = db.executeUpdate(sql, ob)
    print(now_date, temperature, humidity, light, res)
    db.close()


if __name__ == "__main__":
    
    try:
        humidity, temperature = get_tem_and_hum()
        light = get_light()
    
        db = DBTool()
        sql = "select light from tem order by id DESC limit 1"
        result = db.executeQuery(sql, [])
        last_light = ""
        for s in result:
            last_light = str(s[0])
    
        insert_sensor_to_db(humidity, temperature, light)


        if ((light == "1") and last_light == "0") or ((light == "0") and last_light == "1"):
            open_close_curtain(light)
    except Exception as e:
        print(e)


